package com.demo.server.servce;

import com.alibaba.fastjson.JSONObject;
import com.demo.server.pojo.Message;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SelectableChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;

/**
 * @author:谢君臣
 * @Date:2021/7/26-19:33
 * @version:1.0
 * @function:
 */
public class MessagePushImpl implements MessagePush {
    @Override
    public void push(Message message, SocketChannel channel, Selector selector) throws IOException {
        if (message.getReceive().getIp().equals(""))
            pushToALL(message,channel,selector);
        System.out.println(message.toString());
        // message 发送目标用户
    }

    @Override
    public void pushToALL(Message message, SocketChannel channel, Selector selector) throws IOException {
       for(SelectionKey selectionKey:selector.selectedKeys()){
           SocketChannel channel1 = (SocketChannel) selectionKey.channel();
           if (channel1!=channel) {
               ByteBuffer buffer = ByteBuffer.wrap(JSONObject.toJSONBytes(message));
               channel1.write(buffer);
           }
       }
    }
}
